package controllers;

import helpers.CrawlerHelper;
import helpers.UrlHelper;

import java.io.IOException;
import java.util.Map;
import java.util.TreeMap;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.Connection.Response;
import org.jsoup.nodes.Document;

public class CheckHttpHeaderServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException {
		TreeMap<String, String> check = new TreeMap<String, String>();
		String name = (String) request.getParameter("domain");
		Map<String, String> headers = new TreeMap<String, String>();
		
		if (name != null && !UrlHelper.checkDomain(name)) {
			check.put("name", "Please input a valid domain.");
		} else if (name != null) {
			name = UrlHelper.getMainDomain(name);
		} 
		
		
		if (name != null && check.size() == 0) {
			String url = "http://" + name;
			try {
				Connection conn = Jsoup.connect(url);
				Document doc = conn
						.header("accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")
						.header("accept-Language", "en-us,en;q=0.5")
						.userAgent("Mozilla/5.0 (Windows NT 6.1; WOW64; rv:15.0) Gecko/20100101 Firefox/15.0.1")
						.followRedirects(true)
						.timeout(3000)
						.get();
				Response resp = conn.response();
				headers = resp.headers();
				
			} catch (Exception e) {
				// TODO: handle exception
			}
		}
		
		//Cache header
		response.addHeader("Cache-Control", "public, max-age=60000");
		
		request.setAttribute("check", check);
		request.setAttribute("name", name);
		request.setAttribute("headers", headers);
		try {
			request.getRequestDispatcher("/pages/check_http_header.jsp").forward(request, response);
		} catch (ServletException e) {
			e.printStackTrace();
		}
	}
}
